/*
 * @Author: heinan
 * @Date: 2020-07-16 11:33:19
 * @Last Modified by: heinan
 * @Last Modified time: 2023-08-09 21:17:36
 */
"use strict";

const { Service } = require("egg");
const { idCreator } = require("../utils");

class CommentService extends Service {
  async index({ uid, pid, currentPage, pageSize }) {
    const where = {};
    if (uid) {
      where.uid = uid;
    }
    if (uid) {
      where.pid = pid;
    }
    const result = await this.app.mysql.select("comment", {
      where,
      offset: (currentPage - 1) * pageSize,
      limit: parseInt(pageSize),
    });
    const total = await this.app.mysql.count("comment", where);
    return {
      data: result,
      total,
      pageSize: Number(pageSize),
      currentPage: Number(currentPage),
    };
  }
  async destroy({ id }) {
    return await this.app.mysql.delete("comment", { id });
  }
  async update({ id, comment_text }) {
    const $data = { id };
    if (comment_text) {
      $data.comment_text = comment_text;
    }
    return await this.app.mysql.update("comment", $data);
  }
  async create({ uid, pid, comment_text }) {
    const comment_id = idCreator();
    const $data = {
      uid,
      pid,
      comment_text,
      id: comment_id,
      create_time: new Date().getTime(),
    };
    const feedback = await this.app.mysql.get("feedback", { id: pid });
    const comment_ids =
      feedback.comment_ids == undefined || feedback.comment_ids == ""
        ? comment_id
        : `${feedback.comment_ids},${comment_id}`;
    console.log(comment_ids);
    await this.app.mysql.update("feedback", {
      id: pid,
      comment_ids,
    });
    return await this.app.mysql.insert("comment", $data);
  }
}

module.exports = CommentService;

